package com.ljp.server.http;

import com.ljp.RpcApplication;
import com.ljp.model.RpcRequest;
import com.ljp.model.RpcResponse;
import com.ljp.registry.LocalRegistry;
import com.ljp.serializer.Serializer;
import com.ljp.serializer.SerializerFactory;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * ClassName: HttpServerHandler
 * Package: com.ljp.server.http
 * Description:
 *
 * @Author: ljp
 * @Create: 2025/6/4-下午 09:00
 * @Version: 1.0
 */
public class HttpServerHandler implements Handler<HttpServerRequest> {

    @Override
    public void handle(HttpServerRequest request) {
        // 指定序列化器
        final Serializer serializer = SerializerFactory.getInstance(RpcApplication.getRpcConfig().getSerializer());

        // 记录日志
        System.out.println("Received request: " + request.method() + " " + request.uri());

        // 异步处理请求
        request.bodyHandler(body -> {
            byte[] bytes = body.getBytes();
            RpcRequest rpcRequest = null;
            try {
                // 反序列化请求
                rpcRequest = serializer.deserialize(bytes, RpcRequest.class);
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 异步处理响应
            RpcResponse rpcResponse = new RpcResponse();
            if (Objects.isNull(rpcRequest)) {
                rpcResponse.setMessage("request is null");
                doResponse(request, rpcResponse, serializer);
                return;
            }

            try {
                // 获取要调用的服务实现类，通过反射调用
                Class<?> serverClass = LocalRegistry.getServer(rpcRequest.getServiceName());
                Method method = serverClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
                Object result = method.invoke(serverClass.newInstance(), rpcRequest.getArgs());
                // 封装响应
                rpcResponse.setData(result);
                rpcResponse.setDataType(method.getReturnType());
                rpcResponse.setMessage("OK");
            } catch (Exception e) {
                e.printStackTrace();
                rpcResponse.setMessage(e.getMessage());
                rpcResponse.setException(e);
            }
            // 响应
            doResponse(request, rpcResponse, serializer);
        });
    }

    /**
     * 处理响应
     *
     * @param request     请求对象
     * @param rpcResponse 响应对象
     * @param serializer  序列化器
     */
    void doResponse(HttpServerRequest request, RpcResponse rpcResponse, Serializer serializer) {
        HttpServerResponse serverResponse = request.response()
                .putHeader("content-type", "application/json");
        try {
            // 序列化响应
            byte[] serialize = serializer.serialize(rpcResponse);
            serverResponse.end(Buffer.buffer(serialize));
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
